package com.library.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.library.entity.User;

/**
 * 用户登陆后才能访问系统
 */
public class SecurityFilter implements Filter {

	private List<String> passList = new ArrayList<>(); // 完全匹配
	private List<String> passList2 = new ArrayList<>(); // 含通配符*

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;

		// 获得当前请求
		String url = req.getRequestURI(); //包含项目部署名
		url = url.substring(req.getContextPath().length());
		if(!url.startsWith("/")) url = "/" + url;
		
		if(passList.contains(url)) {
			chain.doFilter(req, resp);
			return;
		} else {
			for(String str : passList2) {
				if(url.startsWith(str)) {
					chain.doFilter(req, resp);
					return;
				}
			}
		}
		
		User user = (User) req.getSession().getAttribute("USER");
		if (user == null) {
			// 用户没有登陆，跳转到登陆页面
			resp.sendRedirect(req.getContextPath() + "/endlogin.jsp");
		} else {
			// 用户已登陆，则放行
			chain.doFilter(req, resp);
		}
	}

	@Override
	public void init(FilterConfig cfg) throws ServletException {
		String pass = cfg.getInitParameter("exclude");
		String[] arr = pass.split("\\s*,\\s*");
		for (String str : arr) {
			if (str.endsWith("/*")) {
				passList2.add(str.substring(0, str.length() - 1));
			} else {
				passList.add(str);
			}
		}
	}

}
